package com.yy.wga.admin.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.mp.common.interceptor.RequestUserHolder;
import com.yy.wga.mp.common.utils.common.StringUtils;
import com.yy.wga.mp.common.utils.mapping.BeansUtils;
import com.yy.wga.admin.service.pojo.AdminRoleDO;
import com.yy.wga.admin.service.pojo.AdminRoleMenuDO;
import com.yy.wga.admin.service.pojo.AdminUserRoleDO;
import com.yy.wga.mp.module.admin.mapper.AdminRoleMapper;
import com.yy.wga.mp.module.admin.request.AdminRolePageRequest;
import com.yy.wga.mp.module.admin.request.AdminRoleSaveMenuRequest;
import com.yy.wga.mp.module.admin.request.AdminRoleUpdateStatusRequest;
import com.yy.wga.mp.module.admin.response.AdminRolePageResponse;
import com.yy.wga.mp.module.admin.service.AdminRoleMenuService;
import com.yy.wga.mp.module.admin.service.AdminRoleService;
import com.yy.wga.mp.module.admin.service.AdminUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色信息(AdminRole)表服务实现类
 *
 * @author guochao
 * @since 2024-11-06 22:56:22
 */
@Service
@RequiredArgsConstructor
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRoleDO> implements AdminRoleService {

    private final AdminUserRoleService userRoleService;
    private final AdminRoleMenuService roleMenuService;

    @Override
    public PageBean<AdminRolePageResponse> pageData(AdminRolePageRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<AdminRoleDO> adminRoleList = baseMapper.selectList(new LambdaQueryWrapper<AdminRoleDO>()
                .eq(AdminRoleDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .eq(request.getStatus() != null, AdminRoleDO::getStatus, request.getStatus())
                .like(StringUtils.isNotBlank(request.getName()), AdminRoleDO::getName, request.getName()));
        List<AdminRolePageResponse> responseList = BeansUtils.mapList(adminRoleList, AdminRolePageResponse.class);
        if (!CollectionUtils.isEmpty(responseList)) {
            List<AdminRoleMenuDO> roleMenuList = roleMenuService.list(new LambdaQueryWrapper<AdminRoleMenuDO>()
                    .eq(AdminRoleMenuDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                    .in(AdminRoleMenuDO::getRoleId, responseList.stream().map(AdminRolePageResponse::getId).collect(Collectors.toSet())));

            // 查询菜单
            if (!CollectionUtils.isEmpty(roleMenuList)) {
                Map<Long, List<AdminRoleMenuDO>> roleMap = roleMenuList.stream()
                        .collect(Collectors.groupingBy(AdminRoleMenuDO::getRoleId));
                for (AdminRolePageResponse response : responseList) {
                    List<AdminRoleMenuDO> menuList = roleMap.get(response.getId());
                    if (CollectionUtils.isEmpty(menuList)) {
                        continue;
                    }
                    List<Long> menuIdList = menuList.stream()
                            .map(AdminRoleMenuDO::getMenuId).collect(Collectors.toList());
                    response.setMenuIds(menuIdList);

                }
            }
        }
        PageBean<AdminRolePageResponse> pageBean = new PageBean<>();
        pageBean.setPageInfo(adminRoleList);
        pageBean.setList(responseList);
        return pageBean;
    }

    @Override
    @Transactional
    public void del(Long id) {
        long userRoleCount = userRoleService.count(new LambdaQueryWrapper<AdminUserRoleDO>()
            .eq(AdminUserRoleDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
            .eq(AdminUserRoleDO::getRoleId, id));
        if (userRoleCount > 0) {
            throw new BusinessException("角色已关联用户，不可删除");
        }

        baseMapper.deleteById(id);

        roleMenuService.remove(new LambdaQueryWrapper<AdminRoleMenuDO>()
                .eq(AdminRoleMenuDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .in(AdminRoleMenuDO::getRoleId,id));
    }

    @Override
    @Transactional
    public void saveMenu(AdminRoleSaveMenuRequest request) {
        roleMenuService.remove(new LambdaQueryWrapper<AdminRoleMenuDO>()
                .eq(AdminRoleMenuDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey())
                .in(AdminRoleMenuDO::getRoleId,request.getId()));

        List<AdminRoleMenuDO> roleMenuList = new ArrayList<>(request.getMenuIds().size());
        for (Long menuId : request.getMenuIds()) {
            AdminRoleMenuDO adminRoleMenu = new AdminRoleMenuDO();
            adminRoleMenu.setAppKey(RequestUserHolder.getBaseRequest().getAppKey());
            adminRoleMenu.setRoleId(request.getId());
            adminRoleMenu.setMenuId(menuId);
            roleMenuList.add(adminRoleMenu);
        }
        roleMenuService.saveBatch(roleMenuList);
    }

    @Override
    public void updateStatus(AdminRoleUpdateStatusRequest request) {
        this.update(new LambdaUpdateWrapper<AdminRoleDO>()
                .eq(AdminRoleDO::getAppKey, RequestUserHolder.getBaseRequest().getAppKey()).eq(AdminRoleDO::getId, request.getId())
                .set(AdminRoleDO::getStatus, request.getStatus()));
    }
}
